package com.mhtvs;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import com.mhtvs.MhtvsActivity;
import com.mhtvs.R;
import com.mhtvs.Database.Servers;


//---------------------------------------------------------------
//Development source for MHTVS CLIENT
//"Android client for use with MHTVS"
//Copyright (c) 2011, Doug Thompson, perladdict@gmail.com
//All rights reserved.
//
//http://code.google.com/p/mhtvs/
//
//View Demo here:
//http://www.youtube.com/watch?v=v4M2uVrMrGk
//
//Redistribution and use in source and binary forms, with or
//without modification, are permitted provided that the following
//conditions are met:
//
//* Redistributions of source code must retain the above
//  copyright notice, this list of conditions and the
//  following disclaimer.
//* Redistributions in binary form must reproduce the
//  above copyright notice, this list of conditions and
//  the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//* Neither the name of the developer nor the names
//  of its contributors may be used to endorse or promote
//  products derived from this software without specific
//  prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
//CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
//INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
//MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
//SUCH DAMAGE.
//---------------------------------------------------------------


// Server Entry Screen
public class ServerEntry extends MhtvsActivity {
	/** Called when the activity is first created. */
	private final static String saved_pref_file="saved_port_prefs";
	private static final String PREFS_PRIVATE = null;
	private static final String KEY_PRIVATE = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.server_entry_view);
		//SQLiteDatabase mDatabase;
		//mDatabase = openOrCreateDatabase("ssh_servers.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
		// Fill AutoComplete word list from database
		//fillAutoCompleteFromDatabase();
		// Handle Save Button
		final Button saveServer = (Button) findViewById(R.id.ButtonCreate);
		saveServer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				final EditText ServerName = (EditText) findViewById(R.id.EditTextServerAddress);
				final EditText ServerInternalName = (EditText) findViewById(R.id.EditTextServerInternalAddress);
				final EditText ServerDesc = (EditText) findViewById(R.id.EditTextServerDescription);
				final EditText ServerPassword = (EditText) findViewById(R.id.EditTextServerPassword);
				final EditText ServerSaltPassword = (EditText) findViewById(R.id.EditTextServerSaltPassword);
				final EditText ServerPage = (EditText) findViewById(R.id.EditTextServerPage);
				final EditText ServerUser = (EditText) findViewById(R.id.EditTextServerUser);
				final EditText ServerPort = (EditText) findViewById(R.id.EditTextServerPort);				
				// Save new records
				//deleteDatabase("ssh_servers.db");
				SQLiteDatabase db = mDatabase.getWritableDatabase();
				//db = openOrCreateDatabase("ssh_servers.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
				db.beginTransaction();
				try {
					// check if species type exists already
					long rowId = 0;
					String strServerName = ServerName.getText().toString().toLowerCase();
					String strServerDesc = ServerDesc.getText().toString().toLowerCase();
					String strServerInternal = ServerInternalName.getText().toString().toLowerCase();
					String strServerPassword = ServerPassword.getText().toString().toLowerCase();
					String strServerSaltPassword = ServerSaltPassword.getText().toString().toLowerCase();
					String strServerPage = ServerPage.getText().toString().toLowerCase();
					String strServerUser = ServerUser.getText().toString().toLowerCase();
					String strServerPort = ServerPort.getText().toString().toLowerCase();
					// SQL Query
					SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
					queryBuilder.setTables(Servers.SERVER_TABLE_NAME);
					/////queryBuilder.appendWhere(Servers.SERVER_ADDRESS + "='" + strServerName + "'");
					// run the query
					Cursor c = queryBuilder.query(db, null, null, null, null, null, null);
					if (c.getCount() == 0) {
						// add the new type to our list
						//ContentValues typeRecordToAdd = new ContentValues();
						//typeRecordToAdd.put(Servers.SERVER_ADDRESS, strServerName);
						//rowId = db.insert(Servers.SERVER_TABLE_NAME,Servers.SERVER_ADDRESS, typeRecordToAdd);
						//typeRecordToAdd.put(Servers.SERVER_DESCRIPTION, strServerDesc);
						//rowId = db.insert(Servers.SERVER_TABLE_NAME,Servers.SERVER_DESCRIPTION, typeRecordToAdd);
					} else {
						c.moveToFirst();
						rowId = c.getLong(c.getColumnIndex(Servers.SERVER_TABLE_NAME + "." + Servers.SERVER_ID));
					}
					c.close();
					// Always insert new server records, even if the names clash
					int checkBoxINT;
			        final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
			        if (checkBox.isChecked()) {
			        	checkBoxINT = 1;
			        } else {
			        	checkBoxINT = 0;
			        }
			        
			        int checkBoxINT_b;
			        final CheckBox checkBox_B = (CheckBox) findViewById(R.id.checkBox2);
			        if (checkBox_B.isChecked()) {
			        	checkBoxINT_b = 1;
			        } else {
			        	checkBoxINT_b = 0;
			        }
					
					ContentValues ServerRecordToAdd = new ContentValues();
					ServerRecordToAdd.put(Servers.SERVER_ADDRESS, ServerName.getText().toString());
					ServerRecordToAdd.put(Servers.SERVER_INTERNAL_ADDRESS, ServerInternalName.getText().toString());
					ServerRecordToAdd.put(Servers.SERVER_DESCRIPTION, ServerDesc.getText().toString());
					ServerRecordToAdd.put(Servers.SERVER_PASSWORD, ServerPassword.getText().toString());
					ServerRecordToAdd.put(Servers.SERVER_SALT, ServerSaltPassword.getText().toString());
					ServerRecordToAdd.put(Servers.SERVER_USER, ServerUser.getText().toString());
					ServerRecordToAdd.put(Servers.SERVER_PAGE, ServerPage.getText().toString());
					ServerRecordToAdd.put(Servers.SERVER_PORT, ServerPort.getText().toString());			
			        ServerRecordToAdd.put(Servers.SERVER_ACTIVE_STATE, checkBoxINT);
			        ServerRecordToAdd.put(Servers.SERVER_ACTIVE_INTERNAL_STATE, checkBoxINT_b);
			        
			        db.insert(Servers.SERVER_TABLE_NAME, Servers.SERVER_ADDRESS,ServerRecordToAdd);
			        
					//db.insert(Servers.SERVER_TABLE_NAME, Servers.SERVER_DESCRIPTION,ServerRecordToAdd);
					//ServerRecordToAdd.put(Servers.SERVER_PORTFORWARD_ID_KEY, rowId);
					db.setTransactionSuccessful();
				} finally {
					db.endTransaction();
				}
				// reset form
				ServerName.setText(null);
				ServerDesc.setText(null);
				ServerInternalName.setText(null);
				ServerSaltPassword.setText(null);
				ServerUser.setText(null);
				ServerPort.setText(null);	
				ServerPage.setText(null);
				ServerPassword.setText(null);
				final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
				checkBox.setChecked(false);
				final CheckBox checkBox_B = (CheckBox) findViewById(R.id.checkBox2);
				checkBox_B.setChecked(false);
				db.close();
			}
		});

		// Handle Go to List button
		final Button gotoList = (Button) findViewById(R.id.ButtonShowServers);
		gotoList.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Go to other activity that displays pet list
				startActivity(new Intent(getApplicationContext(), ListServers.class));
			}
		});
		
		final Button  remoteWebview = (Button) findViewById(R.id.ButtonRemoteWebview);
		remoteWebview.setOnClickListener(new Button.OnClickListener() {  
			public void onClick(View v) {
		        startActivity(new Intent(getApplicationContext(), MainView.class));
			}
		});
		
		//final Button rtmp = (Button) findViewById(R.id.ButtonRTMP);
		//rtmp.setOnClickListener(new Button.OnClickListener() {  
		//	public void onClick(View v) {
		//        startActivity(new Intent(getApplicationContext(), RTMPView.class));
		//	}
		//});
		


	}
    
	public void deleteServer(Integer id) {
        SQLiteDatabase db = mDatabase.getWritableDatabase();
		String astrArgs[] = { id.toString() };
        db.delete(Servers.SERVER_TABLE_NAME, Servers.SERVER_ID + "=?",astrArgs );
        db.close();
	}
}